<template>
  <div class="login-page-container">
    <div class="left-section">
      <!-- 左侧蓝色背景和图片区域 -->
      <div class="branding">
        <div class="logo"></div>
        <div class="app-title">安全驾驶培训中心</div>
      </div>
      <div class="illustration">
        <!-- 图片区域 -->
        <img src="@/assets/driving-illustration.png" alt="Driving Illustration" class="driving-img">
      </div>
      <div class="promo-text">
        <h2>专业驾驶培训</h2>
        <p>安全出行保障</p>
      </div>
    </div>

    <div class="right-section">
      <el-card class="login-card">
        <template #header>
          <div class="card-header">
            <h2>驾校管理系统</h2>
            <p>欢迎登录系统</p>
          </div>
        </template>

        <el-tabs v-model="activeTab">
          <el-tab-pane label="学员登录" name="student"></el-tab-pane>
          <el-tab-pane label="教练登录" name="teacher"></el-tab-pane>
          <el-tab-pane label="管理员登录" name="admin"></el-tab-pane>
        </el-tabs>

        <el-form :model="loginForm" :rules="rules" ref="loginFormRef" label-width="0">
          <el-form-item prop="username">
            <el-input v-model="loginForm.username" placeholder="请输入用户名">
              <template #prefix>
                <el-icon><User /></el-icon>
              </template>
            </el-input>
          </el-form-item>

          <el-form-item prop="password">
            <el-input v-model="loginForm.password" type="password" placeholder="请输入密码">
              <template #prefix>
                <el-icon><Lock /></el-icon>
              </template>
            </el-input>
          </el-form-item>

          <el-form-item>
            <el-checkbox v-model="loginForm.remember">记住密码</el-checkbox>
            <el-link type="primary" class="forgot-link">忘记密码？</el-link>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click.prevent="handleLogin" :loading="loading" class="login-button">
              登录
            </el-button>
          </el-form-item>

          <div class="register-link">
            还没有账号？ <el-link type="primary" @click="$router.push('/register')">立即注册</el-link>
          </div>
        </el-form>
      </el-card>

      <div class="copyright">
        © 2024 安全驾驶培训中心版权所有
      </div>
    </div>
  </div>
</template>

<script>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import axios from 'axios'

export default {
  name: 'LoginForm',
  setup() {
    const router = useRouter()
    const loginFormRef = ref(null)
    const loginForm = reactive({
      username: '',
      password: '',
      remember: false
    })
    const activeTab = ref('student')
    const loading = ref(false)

    const rules = {
      username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min:2, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
      ],
      password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, max: 30, message: '长度在 6 到 30 个字符', trigger: 'blur' }
      ]
    }

    const handleLogin = async () => {
      console.log('Login button clicked')
      if (!loginFormRef.value) {
        console.log('loginFormRef is null')
        return
      }

      try {
        console.log('Validating form...')
        await loginFormRef.value.validate()
        console.log('Form validation passed')
        loading.value = true

        // 直接用 JSON 格式提交
        const postData = {
          username: loginForm.username.trim(),
          password: loginForm.password.trim(),
          userType: activeTab.value
        }

        console.log('Sending login request...')
        console.log('Form data:', {
          username: loginForm.username.trim(),
          password: '******',
          userType: activeTab.value
        })

        const response = await axios({
          method: 'post',
          url: '/api/login',
          data: postData
        })

        console.log('Login response:', response)
        if (activeTab.value === 'admin') {
          // 管理员登录成功后跳转到管理员仪表盘
          router.push('/admin-dashboard')
        }
        if (response.data.code === 200) {
          ElMessage.success('登录成功') // 使用 Element Plus 的 ElMessage 组件

          sessionStorage.setItem('account', JSON.stringify(response.data.data))
          console.log("登录信息", sessionStorage.getItem('account'))

          if (loginForm.remember) {
            localStorage.setItem('username', loginForm.username.trim())
            localStorage.setItem('password', loginForm.password.trim())
          }
          if (response.data.data) {
            localStorage.setItem('token', response.data.data)
          }

          // 根据不同的用户类型跳转到不同的页面
          if (activeTab.value === 'teacher') {
            // 教练登录成功后跳转到学员管理页面
            router.push('/student-management')
          } else if (activeTab.value === 'admin') {
            // 管理员登录成功后跳转到管理员仪表盘
            router.push('/admin-dashboard')
          } else {
            // 学员登录后跳转到首页
            router.push('/')
          }
        } else {
          // ElMessage.error(response.data.message || '登录失败')
        }
      } catch (error) {
        console.error('Login error:', error)
        if (error.response) {
          // ElMessage.error(error.response.data.message || '登录失败')
        } else {
          ElMessage.error('登陆失败')
        }
      } finally {
        loading.value = false
      }
    }

    // 检查是否有保存的登录信息
    const checkSavedLogin = () => {
      const savedUsername = localStorage.getItem('username')
      const savedPassword = localStorage.getItem('password')
      if (savedUsername && savedPassword) {
        loginForm.username = savedUsername
        loginForm.password = savedPassword
        loginForm.remember = true
      }
    }

    // 组件挂载时检查保存的登录信息
    checkSavedLogin()

    return {
      loginForm,
      loginFormRef,
      activeTab,
      loading,
      rules,
      handleLogin
    }
  }
}
</script>

<style scoped>
.login-page-container {
  display: flex;
  height: 100vh;
}

.left-section {
  flex: 1;
  background: linear-gradient(180deg, #409EFF, #66B1FF); /* 蓝色渐变 */
  display: flex;
  flex-direction: column;
  color: white;
  padding: 40px; /* 增加内边距 */
}

.branding {
  display: flex;
  align-items: center;
  margin-bottom: auto; /* 将其推到顶部 */
}

.logo {
  width: 24px; /* 调整大小 */
  height: 24px; /* 调整大小 */
  background-color: white; /* 占位符，可以用你的logo */
  border-radius: 50%;
  margin-right: 10px;
}

.app-title {
  font-size: 20px;
  font-weight: bold;
}

.illustration {
  margin-bottom: 30px;
  margin-top: auto; /* 将其推到中心和底部元素之间 */
  text-align: center; /* 居中图片 */
}

.driving-img {
  max-width: 100%;
  height: auto;
  border-radius: 8px;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.3);
}

.promo-text {
    margin-top: auto; /* 将其推到最底部 */
}

.promo-text h2 {
  margin: 0;
  font-size: 28px;
  text-align: center;
}

.promo-text p {
  margin: 10px 0 0;
  font-size: 18px;
  text-align: center;
}

.right-section {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background-color: #ffffff; /* 白色背景 */
  padding: 20px;
  position: relative; /* 用于绝对定位版权信息 */
}

.login-card {
  width: 100%;
  max-width: 400px; /* 控制卡片最大宽度 */
  border-radius: 8px; /* 圆角 */
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1); /* 阴影 */
}

.card-header {
  text-align: center;
  margin-bottom: 20px; /* 增加间距 */
}

.card-header h2 {
  margin: 0;
  font-size: 28px; /* 调整字体大小 */
  color: #333;
}

.card-header p {
  margin: 10px 0 0;
  color: #666;
  font-size: 16px; /* 调整字体大小 */
}

/* 调整Element Plus的Tab样式，使其更紧凑 */
.el-tabs__header {
    margin-bottom: 20px; /* 增加Tabs底部的间距 */
}

.el-form-item {
    margin-bottom: 22px; /* 调整表单项之间的间距 */
}

.login-button {
  width: 100%;
}

.forgot-link {
  float: right;
}

.register-link {
  text-align: center;
  margin-top: 20px;
  font-size: 14px;
}

.copyright {
  position: absolute;
  bottom: 20px;
  right: 20px;
  color: #999;
  font-size: 12px;
}
</style>
